export const Domain = "https://manager.youfengtech.com"
import api from "./index";
const key = 'base64:XMAzKGOMI26XA1WEi1/fmYikv5G1Cm2I7EeaQbA2MpE='
function request (options) {
  console.log('request url:',JSON.stringify(options.url))
  console.log('request data:',JSON.stringify(options.data))
  options.url = options.url.startsWith('http')? options.url:`${Domain}/api${options.url}`
  options.method = options.method || 'post'
  const member = uni.getStorageSync('member')
  options.header = {
    // 'content-type': 'application/json',
    // 'content-type': 'application/x-www-form-urlencoded',
    Authorization: `Bearer ${member.token}`
  }
  let timer = null
  if(!options.no_loading) {
    timer = setTimeout(()=>{  //500ms返回结果的接口不闪提示
      uni.showLoading({
        title: '加载中',
        mask: true
      });
    },500)
  }

  let new_data = options.data || {}

  options.data = new_data

  return new Promise(async (resolve,reject) => {
    try {
      let {data} = await uni.request(options)
      console.log('response data:::',data)
      uni.hideLoading()
      if(timer) { clearTimeout(timer) }

      if (data.code == 0) {
        resolve(data.data)
      } else if([200200].includes(data.code)) {	//token无效,token过期
        console.log('---data.code---',data.code);
        await api.code_to_token() //静默更新token
        request(options)  //重新之前的请求
      } else {
        uni.showToast({
          icon: 'none',
          title: data.msg || '网络错误，请稍后再试'
        })
        reject(data.msg)
      }
    }catch(err){
      uni.hideLoading()
      if(timer) { clearTimeout(timer) }
      console.log('catch err::', err)
      reject(err)
    }
  })
}
export default request


//上传本地文件
export async function uploadFile (params) {
  const member = uni.getStorageSync('member')
  return new Promise(async (resolve,reject) => {
    try {
      let res = await uni.uploadFile({
        url: `${Domain}${params.url || '/api/image/upload'}`,
        filePath: params.filePath || params,
        name: params.name || 'file',
        header: {
           Authorization: `Bearer ${member.token}`
        },
        formData: params.formData || {}
      })
      resolve(JSON.parse(res.data).data)
    }catch (e) {
      reject(e)
    }
  })
}
